package com.appshelves.model.saveable;

import java.io.DataInputStream;
import java.io.IOException;

@SuppressWarnings("serial")
public class ChangeableList<T extends Changeable<T>> extends SaveableList<T> {

    private boolean hasChanged;

    public ChangeableList(Class<T> clazz) {
        super(clazz);
    }

    @Override
    public void clear() {
        super.clear();
        markChanged();
    }

    protected void markChanged() {
        hasChanged = true;
    }

    public boolean addNew(T object) { // load calls 'add', create calls 'addNew'
        super.add(object);
        markChanged();
        return true;
    };

    public void addNew(int index, T object) {
        super.add(index, object);
        markChanged();
    };

    @Override
    public boolean remove(Object object) {
        markChanged();
        return super.remove(object);
    }

    @Override
    public T remove(int index) {
        markChanged();
        return super.remove(index);
    }

    public void save() {
        if (!hasChanged)
            return;
        super.save();
        hasChanged = false;
    }

    /// implementation

    @Override
    protected T createElement(DataInputStream stream, Object arg) throws IOException {
        T el = super.createElement(stream, arg);
        el.setList(this);
        return el;
    }

    /// debug

    protected String logCaption() {
        return super.logCaption() + " has changed: " + hasChanged;
    }
}
